package com.club.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.club.common.constant.Constant;
import com.club.entity.*;
import com.club.mapper.TActPicMapper;
import com.club.mapper.TActivityMapper;
import com.club.mapper.TClubMapper;
import com.club.mapper.UserActRelationMapper;
import com.club.service.TActivityService;
import com.club.util.DateUtil;
import com.club.util.RequestHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhangfc
 * @date 2022/12/12 16:48
 */
@Service
@RequiredArgsConstructor
public class TActivityServiceImpl extends ServiceImpl<TActivityMapper, TActivity>
        implements TActivityService {


    private final TActivityMapper tActivityMapper;
    private final TClubMapper tClubMapper;
    private final UserActRelationMapper userActRelationMapper;
    private final TActPicMapper tActPicMapper;


    /**
     * 活动提交申请
     *
     * @param clubMap 参数
     * @return R
     */
    public R submitAct(Map<String, Object> clubMap) {
        //获取当前用户id
        String userId = RequestHelper.getId();

        TActivity tActivity = Convert.convert(TActivity.class, clubMap);
        tActivity.setActNumber("A" + RandomUtil.randomNumbers(9));
        tActivity.setActStatus(Constant.ActStatus.AUDITING);
        tActivity.setCreateTime(new Date());
        tActivity.setModifyTime(new Date());
        save(tActivity);

        //活动主键
        int actId = tActivity.getActId();
        UserActRelation userActRelation = UserActRelation.builder()
                .actId(actId)
                .userId(Convert.toInt(userId))
                .build();
        userActRelationMapper.insert(userActRelation);
        return R.ok("提交成功");
    }

    /**
     * 活动审核
     *
     * @param actId 主键
     * @param type  类型 1-审核通过 2-审核不通过
     * @return R
     */
    @Override
    public R auditAct(int actId, String type) {
        TActivity tActivity = tActivityMapper.selectById(actId);
        //当前活动的审核状态
        String actStatus = tActivity.getActStatus();
        if (StrUtil.equals(actStatus, Constant.ActStatus.AUDITING)) {
            tActivity.setActStatus(type);
            tActivityMapper.updateById(tActivity);
            return R.ok("操作成功");
        }
        return R.error("当前数据已操作过不允许再次操作");
    }

    /**
     * @param ids 主键集合
     * @return R
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deleteByIds(List<Integer> ids) {
        removeByIds(ids);
        userActRelationMapper.delete(new QueryWrapper<UserActRelation>().in("act_id", ids));
        return R.ok("删除成功");
    }

    /**
     * 根据用户id查询活动列表
     *
     * @param userId 用户id
     * @return R
     */
    @Override
    public R listActByUserId(int userId) {

        List<Map<String, Object>> actMapList = tActivityMapper.listByUserId(userId);
        Map<String, Object> responseMap = new HashMap<>();
        responseMap.put("actList", actMapList);
        return R.ok(responseMap);
    }

    @Override
    public R msgByActId(int actId) {

        Map<String, Object> responseMap = tActivityMapper.msgByActId(actId);
        //封面
        TActPic tActPic = tActPicMapper.selectOne(new QueryWrapper<TActPic>().eq("act_id", actId).eq("iscover", "1"));
        responseMap.put("imgUrl",tActPic.getFilePath());

        Map<String, Object> actFrom = MapUtil.builder(new HashMap<String, Object>())
                .put("actFrom", responseMap)
                .build();

        return R.ok(actFrom);
    }


    /**
     * 分页获取活动列表
     *
     * @param pageBean 分页的信息bean
     * @return R
     */
    @Override
    public R listTactivity(PageBean pageBean) {
        String query = pageBean.getQuery().trim();
        Page<TActivity> actPage = page(new Page<>(pageBean.getPageNum(), pageBean.getPageSize()), new QueryWrapper<TActivity>().like(StrUtil.isNotEmpty(query), "act_number", query));
        List<TActivity> activityList = actPage.getRecords();
        List<Map<String, Object>> activityMapList = activityList.stream()
                .map(activity -> {
                    //根据所属社团的id找到社团
                    int clubId = activity.getClubId();
                    TClub tClub = tClubMapper.selectById(clubId);
                    List<String> aciPicList = tActPicMapper.selectList(new QueryWrapper<TActPic>().eq("act_id", activity.getActId()))
                            .stream()
                            .map(TActPic::getFilePath)
                            .collect(Collectors.toList());
                    //将bean转成Map
                    Map<String, Object> map = BeanUtil.beanToMap(activity);
                    //所属社团的编码
                    map.put("clubNumber", tClub.getClubNumber());
                    map.put("imgUrl", aciPicList);
                    //所属社团的名称
                    map.put("clubName", tClub.getClubName());
                    map.put("createTime", DateUtil.formatDate(activity.getCreateTime(), Constant.TimePlate.STAND_TIME));
                    return map;
                }).collect(Collectors.toList());
        Map<String, Object> responseMap = MapUtil.builder(new HashMap<String, Object>())
                .put("actList", activityMapList)
                .put("total", actPage.getTotal())
                .build();
        return R.ok(responseMap);
    }


}
